/*
 * Main.java
 *
 * Created on __DATE__, __TIME__
 */

package ar.com.bdf.ipharma.protocolo.gui;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.TooManyListenersException;

import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import ar.com.bdf.ipharma.communications.BufferBox;
import ar.com.bdf.ipharma.communications.RunnableLine;
import ar.com.bdf.ipharma.communications.serial.BasicWritePort;
import ar.com.bdf.ipharma.communications.serial.SimpleRead;
import ar.com.bdf.ipharma.protocolo.model.DataTrama;
import ar.com.bdf.ipharma.protocolo.model.FactoryHandShake;
import ar.com.bdf.ipharma.protocolo.model.HandShake;
import ar.com.bdf.ipharma.protocolo.model.ParserTrama;

/**
 *
 * @author  __USER__
 */
public class Main extends javax.swing.JFrame {

	private FactoryHandShake factory = new FactoryHandShake();
	private ParserTrama parser = new ParserTrama();
	private Log log = LogFactory.getLog(Main.class);

	private SimpleRead reader = null;
	private SerialPort  serialPort=null;

	/** Creates new form Main */
	public Main() {
		initComponents();
		initOtherComponents();
	}

	//GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jSeparator1 = new javax.swing.JSeparator();
		jLabel2 = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();
		txtNroSerie = new javax.swing.JTextField();
		btnNodoDesconocido = new javax.swing.JButton();
		jSeparator2 = new javax.swing.JSeparator();
		jLabel6 = new javax.swing.JLabel();
		txtIdentificador = new javax.swing.JTextField();
		jLabel7 = new javax.swing.JLabel();
		btnPedidoIdentificacion = new javax.swing.JButton();
		jSeparator3 = new javax.swing.JSeparator();
		jLabel8 = new javax.swing.JLabel();
		jLabel9 = new javax.swing.JLabel();
		txtNivel = new javax.swing.JTextField();
		jLabel10 = new javax.swing.JLabel();
		txtPosicion = new javax.swing.JTextField();
		jLabel11 = new javax.swing.JLabel();
		txtVueltas = new javax.swing.JTextField();
		txtExpulsion = new javax.swing.JButton();
		jSeparator4 = new javax.swing.JSeparator();
		jLabel12 = new javax.swing.JLabel();
		txtExtraccion = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		txtMensajes = new javax.swing.JTextArea();
		lblMensajes = new javax.swing.JLabel();
		lblPort = new javax.swing.JLabel();
		txtPort = new javax.swing.JTextField();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setTitle("Test Ipharma");
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosed(java.awt.event.WindowEvent evt) {
				formWindowClosed(evt);
			}
		});

		jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel2.setText("Configuraci\u00f3n");

		jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel3.setText("Programaci\u00f3n de ID a un Nodo Desconocido");

		jLabel4.setText("N\u00famero de Serie:");

		txtNroSerie.setText("NNNN");

		btnNodoDesconocido.setText("Ejecutar");
		btnNodoDesconocido
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						btnNodoDesconocidoActionPerformed(evt);
					}
				});

		jLabel6.setText("Identificador del equipo:");

		txtIdentificador.setText("1");

		jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel7.setText("Pedido de Identificaci\u00f3n del Nodo");

		btnPedidoIdentificacion.setText("Ejecutar");
		btnPedidoIdentificacion
				.addActionListener(new java.awt.event.ActionListener() {
					public void actionPerformed(java.awt.event.ActionEvent evt) {
						btnPedidoIdentificacionActionPerformed(evt);
					}
				});

		jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel8.setText("Orden de Expulsi\u00f3n del Medicamento");

		jLabel9.setText("Nivel");

		txtNivel.setText("1");

		jLabel10.setText("Posici\u00f3n");

		txtPosicion.setText("1");

		jLabel11.setText("Vueltas");

		txtVueltas.setText("1");

		txtExpulsion.setText("Ejecutar");
		txtExpulsion.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				txtExpulsionActionPerformed(evt);
			}
		});

		jLabel12.setFont(new java.awt.Font("Tahoma", 1, 12));
		jLabel12.setText("Apertura para Extracci\u00f3n del Medicamento");

		txtExtraccion.setText("Ejecutar");
		txtExtraccion.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				txtExtraccionActionPerformed(evt);
			}
		});

		txtMensajes.setColumns(20);
		txtMensajes.setEditable(false);
		txtMensajes.setRows(5);
		jScrollPane1.setViewportView(txtMensajes);

		lblMensajes.setFont(new java.awt.Font("Tahoma", 1, 12));
		lblMensajes.setText("Enviados/Recibidos");

		lblPort.setText("Puerto:");

		txtPort.setEditable(false);
		txtPort.setText("1");

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout
				.setHorizontalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(jLabel3)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addComponent(
																				jLabel6)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				txtIdentificador,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				52,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGap(
																				18,
																				18,
																				18)
																		.addComponent(
																				lblPort)
																		.addGap(
																				18,
																				18,
																				18)
																		.addComponent(
																				txtPort,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				52,
																				javax.swing.GroupLayout.PREFERRED_SIZE))
														.addComponent(jLabel2)
														.addComponent(jLabel7)
														.addComponent(jLabel8)
														.addComponent(jLabel12)
														.addComponent(
																txtExtraccion,
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(
																jSeparator4,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																418,
																Short.MAX_VALUE)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addComponent(
																				jLabel9)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				txtNivel,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				50,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGap(
																				18,
																				18,
																				18)
																		.addComponent(
																				jLabel10)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				txtPosicion,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				50,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGap(
																				18,
																				18,
																				18)
																		.addComponent(
																				jLabel11)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				txtVueltas,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				50,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																				51,
																				Short.MAX_VALUE)
																		.addComponent(
																				txtExpulsion))
														.addComponent(
																jSeparator3,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																418,
																Short.MAX_VALUE)
														.addGroup(
																layout
																		.createSequentialGroup()
																		.addComponent(
																				jLabel4)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				txtNroSerie,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				62,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED,
																				196,
																				Short.MAX_VALUE)
																		.addComponent(
																				btnNodoDesconocido))
														.addComponent(
																jSeparator2,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																418,
																Short.MAX_VALUE)
														.addComponent(
																jSeparator1,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																418,
																Short.MAX_VALUE)
														.addComponent(
																btnPedidoIdentificacion,
																javax.swing.GroupLayout.Alignment.TRAILING))
										.addGap(18, 18, 18)
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																jScrollPane1,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																265,
																Short.MAX_VALUE)
														.addComponent(
																lblMensajes))
										.addContainerGap()));
		layout
				.setVerticalGroup(layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								layout
										.createSequentialGroup()
										.addGroup(
												layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING,
																false)
														.addGroup(
																javax.swing.GroupLayout.Alignment.LEADING,
																layout
																		.createSequentialGroup()
																		.addGap(
																				26,
																				26,
																				26)
																		.addComponent(
																				lblMensajes)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				jScrollPane1))
														.addGroup(
																javax.swing.GroupLayout.Alignment.LEADING,
																layout
																		.createSequentialGroup()
																		.addContainerGap()
																		.addComponent(
																				jLabel2)
																		.addGap(
																				13,
																				13,
																				13)
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.BASELINE)
																						.addComponent(
																								jLabel6)
																						.addComponent(
																								txtIdentificador,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								lblPort)
																						.addComponent(
																								txtPort,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.PREFERRED_SIZE))
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				jSeparator1,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				2,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				jLabel3)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.BASELINE)
																						.addComponent(
																								jLabel4,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								14,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								btnNodoDesconocido)
																						.addComponent(
																								txtNroSerie,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.PREFERRED_SIZE))
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				jSeparator2,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				10,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				jLabel7)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				btnPedidoIdentificacion)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				jSeparator3,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				10,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				jLabel8)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addGroup(
																				layout
																						.createParallelGroup(
																								javax.swing.GroupLayout.Alignment.BASELINE)
																						.addComponent(
																								jLabel9,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								14,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								txtNivel,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								jLabel10,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								14,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								txtPosicion,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								jLabel11,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								14,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								txtVueltas,
																								javax.swing.GroupLayout.PREFERRED_SIZE,
																								javax.swing.GroupLayout.DEFAULT_SIZE,
																								javax.swing.GroupLayout.PREFERRED_SIZE)
																						.addComponent(
																								txtExpulsion))
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
																		.addComponent(
																				jSeparator4,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				10,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				jLabel12)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				txtExtraccion)))
										.addContainerGap(22, Short.MAX_VALUE)));

		pack();
	}// </editor-fold>
	//GEN-END:initComponents

	private void formWindowClosed(java.awt.event.WindowEvent evt) {
	}

	private void txtExtraccionActionPerformed(java.awt.event.ActionEvent evt) {
		HandShake handler = factory.getApertura(getDataTrama(), 1);
		String serializable = parser.serializable(handler.getRequest());
		sendByCom(serializable);
	}

	private void txtExpulsionActionPerformed(java.awt.event.ActionEvent evt) {
		Integer nivel = Integer.parseInt(txtNivel.getText());
		Integer posicionRulo = Integer.parseInt(txtPosicion.getText());
		Integer cantVueltas = Integer.parseInt(txtVueltas.getText());
		HandShake handler = factory.getExpulsion(getDataTrama(), nivel,
				posicionRulo, cantVueltas);
		String serializable = parser.serializable(handler.getRequest());
		sendByCom(serializable);
	}

	private void btnPedidoIdentificacionActionPerformed(
			java.awt.event.ActionEvent evt) {
		HandShake handler = factory.getIdentificacionNodo(getDataTrama());
		String serializable = parser.serializable(handler.getRequest());
		sendByCom(serializable);
	}

	private void btnNodoDesconocidoActionPerformed(
			java.awt.event.ActionEvent evt) {
		HandShake handler = factory.getNodoDesconocido(Integer.parseInt(txtNroSerie.getText()),
				getDataTrama());
		String serializable = parser.serializable(handler.getRequest());
		sendByCom(serializable);
	}

	private void sendByCom(String serializable) {
		try {
			BasicWritePort handler = new BasicWritePort(getPort());
			handler.write(serializable);
			handler.close();

			log.info(getPort() + "===> " + serializable);
			txtMensajes.setText(txtMensajes.getText() + "\n " + getPort()
					+ "===> " + serializable);

		} catch (Exception e) {
			log.error("ENVIO FALLIDO", e);
		}
	}

	private String getPort() {
		return PropertiesManager.get("port");
	}

	private DataTrama getDataTrama() {
		return new DataTrama(Integer.parseInt(txtIdentificador.getText()));
	}

	public void initOtherComponents() {
		txtPort.setText(getPort());
		RunnableLine runnerLine = new RunnableCom();
		this.reader = new SimpleRead(runnerLine, getPort());
	}

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new Main().setVisible(true);
			}
		});
	}

	//GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JButton btnNodoDesconocido;
	private javax.swing.JButton btnPedidoIdentificacion;
	private javax.swing.JLabel jLabel10;
	private javax.swing.JLabel jLabel11;
	private javax.swing.JLabel jLabel12;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel6;
	private javax.swing.JLabel jLabel7;
	private javax.swing.JLabel jLabel8;
	private javax.swing.JLabel jLabel9;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JSeparator jSeparator1;
	private javax.swing.JSeparator jSeparator2;
	private javax.swing.JSeparator jSeparator3;
	private javax.swing.JSeparator jSeparator4;
	private javax.swing.JLabel lblMensajes;
	private javax.swing.JLabel lblPort;
	private javax.swing.JButton txtExpulsion;
	private javax.swing.JButton txtExtraccion;
	private javax.swing.JTextField txtIdentificador;
	private javax.swing.JTextArea txtMensajes;
	private javax.swing.JTextField txtNivel;
	private javax.swing.JTextField txtNroSerie;
	private javax.swing.JTextField txtPort;
	private javax.swing.JTextField txtPosicion;
	private javax.swing.JTextField txtVueltas;

	// End of variables declaration//GEN-END:variables

	private class RunnableCom implements RunnableLine {
		private BufferBox buffer = new BufferBox(new ShowTextAreaBuffer());

		public void execute(String line) {
			buffer.addInBuffer(line);
		}

		
	}

	private class ShowTextAreaBuffer implements RunnableLine {
		public void execute(String line) {
			line = line.replace("\r\n", "");
			txtMensajes.setText(txtMensajes.getText() + "\n " + getPort()
					+ "<=== " + line);
		}

	}
}